package ar.edu.uba.fi.jmit.receiver;

import java.util.HashMap;
import java.util.Map;

public class ReceiverFactory {

	protected static ReceiverFactory instance;
	
	private Map<String, PollingConsumer> consumers;
	
	private Map<String, Receiver> receivers;
	
	protected ReceiverFactory() {
		consumers = new HashMap<String, PollingConsumer>();
		receivers = new HashMap<String, Receiver>();
	}
	
	public static ReceiverFactory getInstance() {
		if(instance == null) {
			instance = createFactory();
		}
		return instance;
	}

	protected static ReceiverFactory createFactory() {
		return new ReceiverFactory();
	}
	
	public void setPollingConsumer(String name, PollingConsumer consumer) {
		if(consumers.get(name) != null) {
			throw new RuntimeException("There is already a polling consumer for the name " + name);
		}
		this.consumers.put(name, consumer);
	}
	
	public Receiver getReceiver(String name) {
		Receiver receiver = receivers.get(name);
		if(receiver == null) {
			receiver = createReceiver(name);
			receivers.put(name, receiver);
		}
		return receiver;
	}

	private Receiver createReceiver(String name) {
		PollingConsumer consumer = consumers.get(name);
		if(consumer == null) {
			throw new RuntimeException("There is no polling consumer for name " + name);
		}
		return new EventDispatcher(consumer);
	}
}
